package com.example.javawebdemo.filters;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/login.jsp", "/register.jsp", "/HelloServlet"})
public class GuestFilter implements Filter {
    // 白名单允许的action类型
    private static final String[] ALLOWED_ACTIONS = {"login", "register"};

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession(false);

        boolean isLoggedIn = (session != null && session.getAttribute("user") != null);
        String currentAction = request.getParameter("action");

        // Step 1: 检查是否为白名单Action
        if (isAllowedAction(currentAction)) {
            chain.doFilter(request, response);
            return;
        }

        // Step 2: 已登录的访问拦截逻辑
        if (isLoggedIn) {
            redirectToHomePage(request, response);
            return;
        }

        // Step 3: 未登录用户正常放行
        chain.doFilter(request, response);
    }

    /**
     * 检查请求Action是否在白名单中
     */
    private boolean isAllowedAction(String action) {
        if (action == null) return false;
        for (String allowed : ALLOWED_ACTIONS) {
            if (allowed.equalsIgnoreCase(action)) return true;
        }
        return false;
    }

    /**
     * 已登录时的跳转逻辑
     */
    private void redirectToHomePage(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String redirectPath = request.getContextPath() + "/management-Index.jsp";
        response.sendRedirect(redirectPath);
    }
}
